<template>
    <div class="app-container">
      <el-form :model="queryParams" ref="queryForm" size="small" :inline="true" v-show="showSearch" label-width="68px">
        <el-form-item label="产品条码" prop="productSn">
          <el-input style="width: 300px;" v-model="queryParams.productSn" placeholder="请输入产品条码" clearable
            @keyup.enter.native="handleQuery" />
        </el-form-item>
        <el-form-item label="生产时间" prop="productionTime">
          <el-date-picker clearable v-model="queryParams.productionTime" type="date" value-format="yyyy-MM-dd"
            placeholder="请选择生产时间">
          </el-date-picker>
        </el-form-item>
  
        <el-form-item label="是否返工" prop="isRework">
          <el-select v-model="queryParams.isRework" placeholder="请选择是否返工" clearable>
            <el-option v-for="dict in dict.type.yes_or_no" :key="dict.value" :label="dict.label" :value="dict.value" />
          </el-select>
        </el-form-item>
        <el-form-item label="状态" prop="status">
          <el-select v-model="queryParams.status" placeholder="请选择状态" clearable>
            <el-option v-for="dict in dict.type.product_status" :key="dict.value" :label="dict.label"
              :value="dict.value" />
          </el-select>
        </el-form-item>
  
        <el-form-item>
          <el-button type="primary" icon="el-icon-search" size="mini" @click="handleQuery">搜索</el-button>
          <el-button icon="el-icon-refresh" size="mini" @click="resetQuery">重置</el-button>
        </el-form-item>
      </el-form>
  
      <el-row :gutter="10" class="mb8">
        <el-button type="danger" plain icon="el-icon-delete" size="mini" :disabled="multiple" @click="handleDelete"
          v-hasPermi="['mes:productionRecord:remove']">删除
        </el-button>
        <el-col :span="1.5">
          <el-button type="warning" plain icon="el-icon-download" size="mini" @click="downloadExcel"
            v-hasPermi="['mes:productionRecord:export']">导出
          </el-button>
        </el-col>
        <right-toolbar :showSearch.sync="showSearch" @queryTable="getList"></right-toolbar>
      </el-row>
  
      <el-table  v-loading="loading" :data="productionRecordList" @selection-change="handleSelectionChange">
        <el-table-column type="selection" width="55" align="center" />
        <!-- <el-table-column label="ID" align="center" prop="id" /> -->
        <el-table-column label="产品条码" align="center" prop="productSn" width="200">
          <template v-slot="scope">
            <router-link :to="'/production/processing/record/' + scope.row.productSn" class="link-type">
              <span>{{ scope.row.productSn }}</span>
            </router-link>
          </template>
        </el-table-column>
        <el-table-column label="生产时间" align="center" prop="productionTime" width="180" />
        <el-table-column label="生产工艺" align="center" prop="productionProcessName" width="150">
          <template slot-scope="scope">
            <div @click="getRoutlist(scope.row)" style="color: #337ab7;">{{ scope.row.productionProcessName }}</div>
          </template>
        </el-table-column>
        <el-table-column label="返工工艺" align="center" prop="reworkProcessName" />
        <!-- <el-table-column label="加工编码" align="center" prop="processCode"/> -->
        <el-table-column label="是否返工" align="center" prop="isRework">
          <template slot-scope="scope">
            <dict-tag :options="dict.type.yes_or_no" :value="scope.row.isRework" />
          </template>
        </el-table-column>
        <el-table-column label="状态" align="center" prop="status">
          <template slot-scope="scope">
            <dict-tag :options="dict.type.product_status" :value="scope.row.status" />
          </template>
        </el-table-column>
        <el-table-column label="返工次数" align="center" prop="reworkCount" />
        <!-- <el-table-column label="报废原因" align="center" prop="scrapReason" /> -->
        <!-- <el-table-column label="工艺参数" align="center" prop="processParams"> </el-table-column> -->
        <el-table-column label="备注" align="center" prop="remark" />
  
        <!--自定义渲染头-->
        <!-- <el-table-column align="center" :key="index" v-for="(column, index) in columns " :prop="column.prop"
          :label="column.label">
          <el-table-column align="center" :key="index" v-for="(child, index) in column.children "
            :prop="child.prop" :label="child.label" :width="child.width">
            <template slot-scope="scope">
              <dict-tag v-if="child.dist" :options="dict.type[child.dist]" :value="scope.row[child.prop]" />
              <span v-else>{{ scope.row[child.prop] }}</span>
            </template>
          </el-table-column>

        </el-table-column> -->

        <!-- <el-table-column fixed="right" label="操作" align="center" class-name="small-padding fixed-width" width="150">
          <template slot-scope="scope">
            <el-button size="mini" type="text" icon="el-icon-edit" @click="handleRework(scope.row)"
              v-hasPermi="['mes:productionRecord:edit']">返工
            </el-button>
            <el-button size="mini" type="text" icon="el-icon-edit" @click="handleScrap(scope.row)"
              v-hasPermi="['mes:productionRecord:edit']">报废
            </el-button>
          </template>
        </el-table-column> -->
      </el-table>
  
      <pagination v-show="total > 0" :total="total" :page.sync="queryParams.pageNum" :limit.sync="queryParams.pageSize"
        @pagination="getList" />
  
      <!-- 添加或修改生产记录对话框 -->
      <el-dialog :title="title" :visible.sync="open" width="45%" append-to-body>
        <el-form ref="form" :model="form" :rules="rules" label-width="180px">
  
          <el-form-item v-if="flag == 1" label="返工工艺" prop="processId">
            <el-select @change="test" v-model="form.reworkProcessId" placeholder="请选择">
              <el-option v-for="item in processOptions" :key="item.value" :label="item.label" :value="(item.value)"
                :disabled="item.disabled">
              </el-option>
            </el-select>
          </el-form-item>
  
  
          <el-form-item v-if="flag == 2" label="报废原因" prop="scrapReason">
            <el-input v-model="form.scrapReason" type="textarea" placeholder="请输入内容" />
          </el-form-item>
  
        </el-form>
        <div slot="footer" class="dialog-footer">
          <el-button type="primary" @click="submitForm">确 定</el-button>
          <el-button @click="cancel">取 消</el-button>
        </div>
      </el-dialog>
  
  
  
      <el-dialog :title="routeName" :visible.sync="Visiblelook" width="100%">
        <div style="margin: 10 30px;">
          <SerpentineSteps :steps="steps" :currentStep="currentStep" />
        </div>
        <span slot="footer" class="dialog-footer">
          <el-button @click="Visiblelook = false">取 消</el-button>
          <el-button type="primary" @click="Visiblelook = false">确 定</el-button>
        </span>
      </el-dialog>
    </div>
  </template>
  
  <script>
  import {
    listProductionRecord,
    listProductionRecordVo,
    getProductionRecord,
    delProductionRecord,
    addProductionRecord,
    updateProductionRecord
  } from "@/api/mes/production_record";
  import {
    listProcessRoute,
  } from "@/api/mes/process_route";
  import { listProcess } from '@/api/mes/process';
  import SerpentineSteps from "../../../components/SerpentineSteps/index.vue";
  import { reBuild } from '@/utils/tableDataList.js';
  
  import * as XLSX from 'xlsx';
  export default {
  
    name: "ProductionRecord",
    dicts: ['product_status', 'yes_or_no', 'processing_result'],
    components: {
      SerpentineSteps,
    },
    data() {
      return {
        // 遮罩层
        Visiblelook: false,
        loading: true,
        // 选中数组
        ids: [],
        // 非单个禁用
        single: true,
        routeName: '',
        currentStep: 5, // 当前步骤索引，从 0 开始
        // 非多个禁用
        multiple: true,
        // 显示搜索条件
        showSearch: true,
        // 总条数
        total: 0,
        processOptions: [],
        // 生产记录表格数据
        productionRecordList: [],
        // 弹出层标题
        title: "",
        // 是否显示弹出层
        open: false,
        flag: null,
        steps: [],
        // 查询参数
        columnHeaders: {
          productSn: '产品条码',
          productionProcessName: '生产工艺',
          reworkCount: '返工次数',
          // deviceName: '设备名称',
          // workstation: '设备工站',
          // productionTime: '加工时间',
          // processingResult: '加工结果',
          remark: '备注'
        },
        queryParams: {
          pageNum: 1,
          pageSize: 10,
          isFirst:1,
          productSn: null,
          productionTime: null,
          productionProcessId: null,
          reworkProcessId: null,
          processCode: null,
          isRework: null,
          status: null,
          isSample: null,
          reworkCount: null,
          scrapReason: null
        },
        // 表单参数
        form: {},
        // 表单校验
        rules: {},
        columns: []
      };
    },
    created() {
      this.getList();
      this.getProcessList()
    },
    methods: {
      test(value) {
  
        console.log(value)
        console.log(this.form.reworkProcessId)
      },
      /** 查询生产记录列表 */
      getList() {
        this.loading = true;
        listProductionRecordVo(this.queryParams).then(response => {
          let { rows } = response
          // this.reBuildData(rows)
          this.productionRecordList = rows;
          this.total = response.total;
          this.loading = false;
        });
      },
      reBuildData(list) {
        let { columns, rows } = reBuild(list)
        this.columns = columns
        this.productionRecordList = rows;
      },
      // 取消按钮
      cancel() {
        this.open = false;
        this.reset();
      },
      parseJson(str) {
        return str ? JSON.parse(str) : [];
      },
      // 表单重置
      reset() {
        this.form = {
          id: null,
          productSn: null,
          productionTime: null,
          productionProcessId: null,
          reworkProcessId: null,
          processCode: null,
          isRework: null,
          status: null,
          reworkCount: null,
          scrapReason: null,
          createBy: null,
          isFirst:null,
          createTime: null,
          updateBy: null,
          updateTime: null,
          remark: null
        };
        this.resetForm("form");
      },
      /** 搜索按钮操作 */
      handleQuery() {
        this.queryParams.pageNum = 1;
        this.getList();
      },
      /** 重置按钮操作 */
      resetQuery() {
        this.resetForm("queryForm");
        this.handleQuery();
      },
      //工艺
      getProcessList() {
        let queryParams = {
          pageNum: 1,
          pageSize: 100,
          processType: 2
        }
        listProcess(queryParams).then(response => {
          this.processOptions = this.buildOptions(response.rows, { value: 'id', label: 'processName' });
        });
      },
      buildOptions(rows, op) {
        return rows.map(item => {
          return {
            value: item[op.value],
            label: item[op.label]
          }
        })
      },
      // 多选框选中数据
      handleSelectionChange(selection) {
        this.ids = selection.map(item => item.id)
        this.single = selection.length !== 1
        this.multiple = !selection.length
      },
      /** 新增按钮操作 */
      handleAdd() {
        this.reset();
        this.open = true;
        this.title = "添加生产记录";
      },
      /** 修改按钮操作 */
      handleRework(row) {
        this.flag = 1
        this.reset();
        const id = row.id || this.ids
        getProductionRecord(id).then(response => {
          this.form = response.data;
          this.open = true;
          this.title = "修改返工路径";
        });
      },
      //报废
      handleScrap(row) {
        this.flag = 2
        this.reset();
        const id = row.id || this.ids
        getProductionRecord(id).then(response => {
          this.form = response.data;
          this.open = true;
          this.title = "报废原因";
        });
      },
      /** 提交按钮 */
      submitForm() {
  
        this.$refs["form"].validate(valid => {
          if (valid) {
            this.form.isRework = 1
            this.form.reworkCount = this.form.reworkCount + 1
            this.form.status = 3
            // this.form.
            console.log(this.form.reworkProcessId);
            if (this.form.id != null) {
              updateProductionRecord(this.form).then(response => {
                this.$modal.msgSuccess("修改成功");
                this.open = false;
                this.getList();
              });
            } else {
              console.log("这里是新增");
              return
              addProductionRecord(this.form).then(response => {
                this.$modal.msgSuccess("新增成功");
                this.open = false;
                this.getList();
              });
            }
          }
        });
      },
      /** 删除按钮操作 */
      handleDelete(row) {
        const ids = row.id || this.ids;
        this.$modal.confirm('是否确认删除生产记录编号为"' + ids + '"的数据项？').then(function () {
          return delProductionRecord(ids);
        }).then(() => {
          this.getList();
          this.$modal.msgSuccess("删除成功");
        }).catch(() => {
        });
      },
      /** 导出按钮操作 */
      downloadExcel() {
        const data = (this.productionRecordList || []).map(row => {
          return Object.keys(row).reduce((obj, key) => {
            let label = this.columnHeaders ? this.columnHeaders[key] : undefined;
            if (label) {
              if (key === 'processingResult') {
                obj[label] = row[key] == 1 ? '合格' : '不合格';
              } else {
                obj[label] = row[key];
              }
            } else {
              if (this.containsChinese && this.containsChinese(key)) {
                obj[key] = row[key];
              }
            }
            return obj;
          }, {});
        });
  
        if (data.length > 0) {
          const ws = XLSX.utils.json_to_sheet(data);
          const wb = XLSX.utils.book_new();
          XLSX.utils.book_append_sheet(wb, ws, 'Sheet1');
          XLSX.writeFile(wb, '加工过程.xlsx');
        } else {
          console.error('No data available to export!');
        }
      },
      containsChinese(str) {
        const regex = /[\u4e00-\u9fa5]+/;
        return regex.test(str);
      },
      getRoutlist(row) {
        console.log(row);
        let queryParams = {
          pageNum: 1,
          pageSize: 100,
          processId: row.productionProcessId
        }
        listProcessRoute(queryParams).then(response => {
          this.steps = response.rows;
          this.routeName = row.productionProcessName + "路径"
          this.Visiblelook = true
        });
      }
    }
  };
  </script>
  
  
  <style>
  /* 定义滚动条轨道的样式 */
  ::-webkit-scrollbar {
    width: 8px;
    /* 滚动条轨道的宽度 */
    height: 12px;
  }
  </style>
  